package com.windsea.relationshipmining.services;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.windsea.relationshipmining.api.ContactApi;
import com.windsea.relationshipmining.database.DBUserData;

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.os.Looper;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.util.Log;

public class LogCallHistory extends Service {

	// private static final String TAG = LogCallHistory.class.getSimpleName();
	public DBUserData dbUserData;
	public MyCallLogCollector updater;
	public boolean isRunning = false;

	String contactID, datetime, time, name, phonenumber, duration, callType;

	int tmp1;

	// Specify formatting of data and time
	SimpleDateFormat formatdatetime = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	// Specify interpretation of Call-Type
	public String callType(int t) {

		String g = null;

		switch (t) {
		case Calls.INCOMING_TYPE:
			g = "Incoming";
			break;
		case Calls.OUTGOING_TYPE:
			g = "Outgoing";
			break;
		case Calls.MISSED_TYPE:
			g = "Missed";
			break;
		}
		return g;

	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();

		dbUserData = new DBUserData(getApplicationContext());
		updater = new MyCallLogCollector();

		// Log.d(TAG, "Collecting Call History");

	}

	@SuppressWarnings("deprecation")
	@Override
	public synchronized void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		// Starting the Service is only possible if it's not already running

		if (!this.isRunning) {
			updater.start();
			this.isRunning = true;
			// Log.d(TAG, "Started LogCallHistory");
		}

	}

	@Override
	public synchronized void onDestroy() {
		super.onDestroy();

		if (this.isRunning) {
			updater.interrupt();
			this.isRunning = false;
			// Log.d(TAG, "Destroyed LogCallHistory");
			updater = null; // for garbage collection
			// Start LogSMSHistory Service
			Intent intentLogSMSHis = new Intent(getApplicationContext(),
					LogSMSHistory.class);
			startService(intentLogSMSHis);
		}

	}

	// ////// Private-Updater Thread /////////

	class MyCallLogCollector extends Thread {

		static final long DELAY = 1000; // 1s intervals between consequent calls

		@Override
		public void run() {

			boolean status = true;

			try {
				Cursor c = getContentResolver().query(
						android.provider.CallLog.Calls.CONTENT_URI, null, null,
						null, android.provider.CallLog.Calls.DATE + " ASC");

				if (c.moveToFirst()) {

					// Open Database
					dbUserData.open();
					// Iteration-variable;
					// int i = 1;

					// Check: Still valid entry left?
					while (!c.isAfterLast()) {

						// Collect History
						int callID = c.getInt(c
								.getColumnIndex(CallLog.Calls._ID));
						long tmp = c.getLong(c
								.getColumnIndex(CallLog.Calls.DATE));
						Date d = new Date(tmp);
						datetime = formatdatetime.format(d);

						phonenumber = ContactApi.phoneNumberProcess(c
								.getString(c
										.getColumnIndex(CallLog.Calls.NUMBER)));
						if ((contactID = dbUserData
								.getContactIdByPhonenumber(phonenumber)) != null) {

							duration = c.getString(c
									.getColumnIndex(CallLog.Calls.DURATION));
							tmp1 = c.getInt(c
									.getColumnIndex(CallLog.Calls.TYPE));
							callType = callType(tmp1);

							// Log History
							// Log.d(TAG, "Entry number: " + i);
							// Log.d(TAG, datetime);
							// Log.d(TAG, contactID);
							// Log.d(TAG, duration);
							// Log.d(TAG, callType);

							// Write History
							dbUserData.insertCallLogs(callID, datetime,
									contactID, duration, callType);
							dbUserData.hasAtLeastACall(contactID, 1);
							// i++;
						}
						// }

						// Move to the next entry
						c.moveToNext();

						// Wait till next call
						// Log.d(TAG, "-- Updater Sleeping --");
						// Thread.currentThread();
						// Thread.sleep(DELAY);
					}

				}

				c.close();
				dbUserData.close();

				if (status) {
					Looper.prepare();
					status = false;
				}

			} catch (Exception e) {
				// Interrupted
				isRunning = false;
			}

			// ////////////////////// End of Call History Collection
			// //////////////////////////
			// Kill this Service //
			// Log.d(TAG, "Killing CallHistoryService!");
			stopSelf();

		}

	}

	public boolean isRunning() {
		return this.isRunning;
	}

}